package com.hejjon.syyapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.hejjon.syyapi.bean.ConnectionInfo;
import com.hejjon.syyapi.dao.IXDbInfoDao;
import com.hejjon.syyapi.entity.XDbInfo;
import com.hejjon.syyapi.service.IDbInfoService;
import com.hejjon.syyapi.vo.DBConfig;
import com.kern.framework.bean.ResponseResult;
import com.kern.framework.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by caoshi at 14:07 2021-10-10
 */
@Service
public class XDbInfoServiceImpl implements IDbInfoService {

    @Autowired
    private IXDbInfoDao dbInfoDao;


    @Override
    public ResponseResult saveOrUpdate(DBConfig dbConfig) {
        String id = dbConfig.getId();
        Date date = new Date();
        XDbInfo dbInfo = null;
        if (StringUtils.isEmpty(id)) {      // 新增
            dbInfo = new XDbInfo();
            String uuid = StringUtil.getUUID();
            dbInfo.setId(uuid);
            setDbInfo(dbConfig, dbInfo);
            dbInfo.setCreateTime(date);
        } else {    // 更新
            if (dbInfoDao.existsById(id)) {
                dbInfo = dbInfoDao.getOne(id);
                setDbInfo(dbConfig, dbInfo);
                dbInfo.setUpdateTime(date);
            }
        }
        dbInfoDao.saveAndFlush(dbInfo);
        return new ResponseResult(0, "数据源信息保存成功", "", dbInfo);
    }

    @Override
    public ResponseResult getByName(String name) {
        XDbInfo db = null;
        if (StringUtils.isNotEmpty(name)) {
            db = dbInfoDao.findByName(name);
        }
        return new ResponseResult(0, "", "", db);
    }

    @Override
    public ResponseResult getById(String id) {
        return null;
    }


    private void setDbInfo(DBConfig dbConfig, XDbInfo dbInfo) {
        if (dbConfig == null || dbInfo == null) return;
        dbInfo.setName(dbConfig.getName());
        dbInfo.setAlias(dbConfig.getAlias());
        dbInfo.setViewName(dbConfig.getAlias());
        dbInfo.setDescription(dbConfig.getDescription());
        ConnectionInfo connInfo = dbConfig.getConnInfo();
        String connInfoStr = JSON.toJSONString(connInfo);
        dbInfo.setConnInfo(connInfoStr);
    }


}
